<template>
  <div>
   <!--面包屑-->
    <el-breadcrumb separator="/" style="font-size: 12px;padding-bottom: 10px;padding-left: 10px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>附件管理</el-breadcrumb-item>
    </el-breadcrumb>

     <!--文件列表卡片-->
    <el-card class="box-card">
      <!--搜索，添加等-->
      <el-form  class="demo-form-inline" :inline="true" :model="fileVO">
        <el-form-item label="文件名">
          <el-input @keyup.enter.native="search" clearable="" @clear="search" v-model="fileVO.fileName"
                    placeholder="文件名"></el-input>
        </el-form-item>
        <el-form-item label="文件类型" >
          <el-input @keyup.enter.native="search" clearable="" @clear="search" v-model="fileVO.type"
                    placeholder="文件类型"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-refresh" @click="resetFileVo">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button type="success" icon="el-icon-plus" @click="show">上传</el-button>
          <el-button type="warning" icon="el-icon-delete" @click="deleteFiles" :disabled="this.select.length === 0">批删</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table
        :data="fileList"
        border
        max-height="500"
        style="width: 100%"
        @selection-change="selectChange">
        <el-table-column
          type="selection"
          width="40">
        </el-table-column>
        <el-table-column
          prop="id"
          label="#"
          width="50">
        </el-table-column>
        <el-table-column
          prop="fileName"
          label="文件名"
          width="150">
        </el-table-column>

        <el-table-column
          prop="url"
          label="文件地址"
          width="500">
          <template slot-scope="scope">
            <a :href="scope.row.url">
              {{scope.row.url}}
            </a>
          </template>
        </el-table-column>

        <el-table-column
          prop="size"
          sortable=""
          label="文件大小"
          width="150">
        </el-table-column>

        <el-table-column
          prop="type"
          label="文件格式"
          width="150">
        </el-table-column>

        <el-table-column
          prop="createTime"
          sortable=""
          label="上传时间"
          width="200">
        </el-table-column>

        <el-table-column
          label="操作"
          header-align="center"
          fixed="right"
          width="140">
          <template slot-scope="scope">
            <el-button style="margin-left: 15px"
                       type="primary"
                       size="mini"
                       icon="el-icon-download"
                       @click="download(scope.row)"></el-button>
            <el-button style="margin-left: 15px"
                       type="warning"
                       size="mini"
                       icon="el-icon-delete"
                       @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        style="padding-top: 15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="total"
        :current-page="current"
        :page-sizes="[6, 10, 20, 30]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <FileAdd :addOrUpdateVisible="addOrUpdateVisible"
               @changeShow="showAddOrUpdate"
               @fresh="fresh">
      </FileAdd>
    </el-card>
    </div>
</template>
<script>
import {deleteImgFile, deleteFiles, fileDownload} from '@/api/oss'
import {deleteFileById, deleteFilesByIds, findFileList} from '@/api/system/file'
import FileAdd from '@/views/files/FileAdd'

export default {
  name:'Files',
  components:{
    FileAdd
  },
  props:{
    field :{
      type: String,
      default: 'avatar'
    },
    //上传地址
    url:{
      type:String,
      default:''
    }
  },
  data(){
    return{
      fileVO:{
        fileName:'',
        type:'',
        url:''
      },
      fileList:[],
      total: 100,
      current: 1,
      size: 6,
      select:[],//选中的值显示
      addOrUpdateVisible: false,
    }
  },
  created(){
    this.fresh()
  },
  methods:{
    async getFileList(){
      const {data : res} = await findFileList(this.current,this.size,this.fileVO)
      console.log(res)
      this.total = res.total
      this.fileList = res.records
    },
    //刷新页面
    fresh(){
      this.getFileList()
    },
    //搜索
    search(){
      this.current = 1
      this.fresh()
    },
    //重置表单
    resetFileVo () {
      this.fileVO.type = ''
      this.fileVO.fileName = ''
      this.fresh()
    },
    //多选框发生变化
    selectChange (sels) {
      this.select = sels
    },
    //显示文件添加页面
    show(){
      console.log(111);
      this.addOrUpdateVisible = true;
    },
    //批量删除
    async deleteFiles(){
      //获取所有选中行的id组成的字符串，以逗号隔开
       const ids = this.select.map(item => item.id).join()
       //获取所有选中行的url组成的字符串，以逗号隔开
       const urls = this.select.map(item => item.url).join()
       console.log(ids)
       const res = await this.$confirm(
         '是否删除这'+this.select.length+ '个文件?',
         '提示',
         {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
        }).catch(()=>{
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })

      if(res === 'confirm'){
        const res = await deleteFilesByIds(ids)
        const resp = await deleteFiles(urls)

        if(res.code === 200 && resp.code === 200){
          this.$message.success('删除文件成功')
          this.fresh()
        }else{
          this.$message.error(res.msg)
        }
      }
    },
    //下载文件
    async download(row){
      const filename = row.url.split('.com/')[1];
       await fileDownload(filename).then(res =>{

          let url = window.URL.createObjectURL(new Blob([res]))//将二进制文件转化为可访问的url
          var a = document.createElement('a')
          document.body.appendChild(a)
          a.href = url
          a.download = filename
          a.click()
          
          window.URL.revokeObjectURL(url)
       }).catch(err =>{
        this.$notify.fail({
            title: '操作失败',
            message : '下载文件失败',
          })
      })
        
    },
    async deleteAliFile(file){
     await deleteImgFile(file)
      
    },
    async deleteFileInMysql(id){
      const res = await deleteFileById(id)
      console.log(res)
      if(res.code == 200){
        this.$notify.success({
          title: '操作成功',
          message: '文件删除'
        })
        //刷新数据
        this.getFileList()
      }else{
        return this.$message.error('删除失败'+res.message)
      }
    },
    //单个删除操作
    handleDelete(row){
      this.$confirm('删除操作，是否继续?','提示',{
        confirmButtonText:'确定',
        cancalButtonText:'取消',
        type: 'warning'
      }).then(()=>{
        this.deleteFileInMysql(row.id)
        this.deleteAliFile(row.url)
      }).catch(()=>{
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },   
    //监听子组件弹窗关闭后触发，由子组件调用
    showAddOrUpdate(data){
      console.log(data);
      if(data === 'false'){
        this.addOrUpdateVisible = false
      }else{
        this.addOrUpdateVisible = true
      }
    },
     //当每页条数改变
    handleSizeChange (val) {
      this.size = val
      this.getFileList()
    },
    //当前页码改变
    handleCurrentChange (val) {
      this.current = val
      this.getFileList()
    },

  }
  
}
</script>
<style>

</style>